﻿Imports System.IO
Imports Ionic.Utils.Zip

Public Class ZipHelper

    ''' <summary>
    ''' Adds the confirm files to zip file.
    ''' </summary>
    ''' <param name="baseFilePath">The base file path.</param>
    ''' <param name="fileList">The file list.</param>
    ''' <param name="zipFilePath">The zip file path.</param>
    Public Shared Sub AddFilesToZip(ByVal baseFilePath As String, ByVal fileList() As String, ByVal zipFilePath As String, ByVal folderNameInZip As String)
        ZipHelper.CheckAndCreateZipFile(zipFilePath)
        Using zip As ZipFile = ZipFile.Read(zipFilePath)
            For Each sourceFile In fileList
                zip.AddFile(Path.Combine(baseFilePath, sourceFile), folderNameInZip)
            Next
            zip.Save()
        End Using
    End Sub


    ''' <summary>
    ''' Checks the and creates an empty zip file if necessary.
    ''' </summary>
    ''' <param name="zipFilePath">The zip file path.</param>
    Private Shared Sub CheckAndCreateZipFile(ByVal zipFilePath As String)
        Dim archiveFolder = Path.GetDirectoryName(zipFilePath)
        If Not Directory.Exists(archiveFolder) Then
            Directory.CreateDirectory(archiveFolder)
        End If
        If Not File.Exists(zipFilePath) Then
            Using zip As New ZipFile(zipFilePath)
                zip.Save()
            End Using
        End If
    End Sub

    Public Shared Sub ExtractZipFile(ByVal fileNameInZip As String, ByVal zippedFile As Byte(), ByVal targetFilePath As String)
        Dim tempFolder = Path.Combine(Path.GetTempPath(), "Archives_" + Guid.NewGuid().ToString())

        'Save the zip file to a temp location
        Dim tempZipFileName = Path.GetTempFileName()
        File.WriteAllBytes(tempZipFileName, zippedFile)

        'Unzip the contents to another temp location
        Dim targetFolder = Path.GetDirectoryName(targetFilePath)
        Using zip As ZipFile = ZipFile.Read(tempZipFileName)
            zip.Extract(fileNameInZip, tempFolder)
        End Using

        CheckAndCreateFolder(Path.GetDirectoryName(targetFilePath))
        'Move the unzipped file to the specified location
        File.Move(Path.Combine(tempFolder, fileNameInZip), targetFilePath)

        Try 'Cleanup
            File.Delete(tempZipFileName)
            Directory.Delete(tempFolder)
        Catch ex As Exception
            'No worries if there are errors cleaning up
        End Try
    End Sub

    Private Shared Sub CheckAndCreateFolder(ByVal path As String)
        If Not Directory.Exists(path) Then
            Directory.CreateDirectory(path)
        End If
    End Sub
End Class
